<template>
  <!-- 搜索框 -->
  <form action="/">
    <van-search
        v-model="searchText"
        placeholder="请输入搜索标签"
        show-action
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>
  <!-- 已筛选标签 -->
  <van-divider content-position="left">已筛选标签</van-divider>
  <div v-if="activeIds.length === 0">
    请选择标签
  </div>
  <van-space :size="10" v-for="id in activeIds" style="margin: 0px 5px;">
    <van-tag type="success">{{ id }}</van-tag>
  </van-space>

  <!-- 全部标签 -->
  <van-divider content-position="left">全部标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />
  <div style="padding: 10px;">
    <van-button block type="primary" @click="doSearch">搜索</van-button>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import request from "../request/request";
import {Tag} from "vant";
const router = useRouter();

const searchText = ref('');

const activeIds = ref([]);
const activeIndex = ref(0);

// 原始数据
const originalTagList = [
  {
    text: '学习方向',
    children: [
      { text: 'Java', id: 'Java' },
      { text: 'C++', id: 'C++' },
      { text: '前端', id: '前端' },
    ],
  },
  {
    text: '年级',
    children: [
      { text: '大一', id: '大一' },
      { text: '大二', id: '大二' },
      { text: '大三', id: '大三' },
    ],
  }
];

const tagList = ref(originalTagList);

// 获取全部标签(带层次)
onMounted(async () => {
  // 调用后台接口数据
  const res = await request.get('/tags/list/group');
  if (res.data && res.data?.code === 200) {
    // 获取成功
    const rootTagList = res.data.data;
    // TODO：需要优化性能
    console.log(rootTagList)
    let tmpTagList = [];
    for (let rootTag of rootTagList) {
      let tmpRootTag = {
        text: '',
        children: []
      };
      let children = rootTag.children;
      let tmpChildren = [];
      for (let child of children) {
        let tmpChild = {
          text: '',
          id: ''
        };
        tmpChild.text = child.tagName;
        tmpChild.id = child.tagName;
        tmpChildren.push(tmpChild);
      }
      tmpRootTag.text = rootTag.tagName;
      tmpRootTag.children = tmpChildren;
      tmpTagList.push(tmpRootTag);
    }
    tagList.value = tmpTagList;
  }
});

const onCancel = () => {
  // 重置搜索内容
  searchText.value = ''
  tagList.value = originalTagList
};

const onSearch: (text: string) => void = (text: string) => {
  tagList.value = originalTagList.map(parentTag => {
    let tmpParentTag = {...parentTag}
    tmpParentTag.children = tmpParentTag.children.filter(item => {
      return item.text.includes(searchText.value)
    })
    return tmpParentTag;
  })
};

// 点击搜索按钮触发事件
const doSearch = () => {
  router.push({
    path: '/user/list',
    query: {
      tagList: activeIds.value
    }
  })
};
</script>

<style scoped>

</style>